//
//  YCNewFeatureView.swift
//  WeiboDemo
//
//  Created by 尹成 on 2017/1/18.
//  Copyright © 2017年 yc. All rights reserved.
//

import UIKit

class YCNewFeatureView: UIView {

    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var enterButton: UIButton!
    @IBOutlet weak var pageControl: UIPageControl!
    
    @IBAction func enterAction(_ sender: UIButton) {
        removeFromSuperview()
    }
    
    class func loadFromXib() -> YCNewFeatureView {
        let nib = UINib.init(nibName: "YCNewFeatureView", bundle: nil)
        let vc = nib.instantiate(withOwner: self, options: [:])[0] as? YCNewFeatureView
        
        vc?.frame = UIScreen.main.bounds
        return vc!
    }
    
    override func awakeFromNib() {
        let count = 4
        let rect = UIScreen.main.bounds
        
        pageControl.numberOfPages = count
        
        for i in 0..<count {
            let imageName = "new_feature_h_\(1)"
            let iv = UIImageView(image: UIImage(named:imageName))
            //设置大小
            iv.frame = rect.offsetBy(dx: CGFloat(i)*rect.width, dy: 0)
            scrollView.addSubview(iv)
         }
        
        scrollView.contentSize = CGSize(width: CGFloat(count+1)*rect.width, height: rect.height)
        scrollView.delegate = self
    }
    
}

extension YCNewFeatureView:UIScrollViewDelegate{
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        enterButton.isHidden = (page != scrollView.subviews.count - 1)
        
        if page == scrollView.subviews.count {
            removeFromSuperview()
        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        enterButton.isHidden = true
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5)
        pageControl.currentPage = page
        pageControl.isHidden = (page == scrollView.subviews.count)
    }
}
